package com.katsu.myapplib.util;

import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;

public final class UtilClear {

    private UtilClear() {}

    public static void clear(Object o) {

        try {

            co(o);

        } catch (Exception e) {}

        System.gc();
//		System.exit(0);
    }

    private static void co(Object o) throws Exception {

        Field[] fs = o.getClass().getDeclaredFields();

        if (fs != null && fs.length > 0) {

            for (Field f : fs) {

                try {

                    f.setAccessible(true);

                    Object oo = f.get(o);

                    if (oo != null) {

                        cf(oo);

                        f.set(o, null);

                    }

                    f.setAccessible(false);

                } catch (Exception e) {}

            }

        }

    }

    @SuppressWarnings("rawtypes")
    private static void cf(Object o) {

        if (o instanceof Collection<?>) {

            Collection c = (Collection) o;

            for (Object oo : c) {

                cf(oo);

            }

            c.clear();

        } else if(o instanceof Map<?, ?>) {

            Map m = (Map) o;

            Collection c = m.values();

            for (Object oo : c) {

                cf(oo);

            }

            m.clear();

        } else if(o instanceof ViewGroup) {

            cvg((ViewGroup)o);

        } else if(o instanceof Bitmap) {

            ((Bitmap) o).recycle();

        }

    }

    private static void cvg(ViewGroup vg) {

        try {

            for (int i = 0; i < vg.getChildCount(); i++) {

                View v = vg.getChildAt(i);

                if (v instanceof ViewGroup) {

                    cvg((ViewGroup) v);

                }

            }

            vg.removeAllViews();

        } catch (Exception e) {}

    }

}
